package com.dianpingmedia.wifitz.ui;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputLayout;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.dianpingmedia.wifitz.R;
import com.dianpingmedia.wifitz.WifiService;
import com.dianpingmedia.wifitz.utlis.SPUtils;
import com.dianpingmedia.wifitz.utlis.SerialPortFinder;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
    private TextView mTextView;
    private TextView mSizeTextView;
    private TextView mLogTextView;
    private ScrollView mScrollView;
    private ScrollView mLogScrollView;
    private ServiceConnection mConn;
    private int mMacCount = 30;
    private int mLogCount = 30;
    private Pattern m_ipPattern = Pattern.compile("^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$");
    private String[] m_ttyDevices = new SerialPortFinder().getAllDevices();
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            CharSequence str = (CharSequence) msg.obj;
            if (!TextUtils.isEmpty(str)) {
                switch (what) {
                    case 0:
                        mMacCount--;
                        if (mMacCount < 0) {
                            mTextView.setText("");
                            mMacCount = 30;
                        }
                        mTextView.append(str);
                        mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        break;
                    case 1:
                        mLogCount--;
                        if (mLogCount < 0) {
                            mLogTextView.setText("");
                            mLogCount = 30;
                        }
                        mLogTextView.append("\n" + str);
                        mLogScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        break;
                    case 2:
                        mSizeTextView.setText(str);
                        break;
                }
            }
        }
    };
    private EditText mEdt_ip;
    private EditText mEdt_port;
    private EditText mEdt_unit;
    private EditText mEdt_usbtty;
    private EditText mEdt_rang;
    private TextInputLayout m_ipTil;
    private TextInputLayout m_portTil;
    private DrawerLayout mDrawerLayout;
    private FloatingActionButton mFabutton;
    private WifiService mService;
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindService();
        initDatas();
    }


    private void bindService() {
        try {
            Intent wifiServiceIntent = new Intent(this, WifiService.class);
            mConn = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    mService = ((WifiService.WifiBinder) service).getService();
                    mService.setHandler(mHandler);
                    mService.start();
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }
            };
            this.bindService(wifiServiceIntent, mConn, Context.BIND_AUTO_CREATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initDatas() {
        mTextView = this.findViewById(R.id.macs);
        mLogTextView = this.findViewById(R.id.logs);
        mScrollView = this.findViewById(R.id.scrollView);
        mLogScrollView = this.findViewById(R.id.logs_scroll);
        mSizeTextView = this.findViewById(R.id.size);
        mEdt_ip = this.findViewById(R.id.ip);
        mEdt_port = this.findViewById(R.id.port);
        mEdt_unit = this.findViewById(R.id.unit);
        mEdt_usbtty = this.findViewById(R.id.usbtty);
        mEdt_rang = this.findViewById(R.id.rang);
        mDrawerLayout = this.findViewById(R.id.drawer_layout);
        mFabutton = this.findViewById(R.id.fabutton);
        ListView m_ttyList = this.findViewById(R.id.ttyList);
        m_ipTil = this.findViewById(R.id.ip_til);
        m_portTil = this.findViewById(R.id.port_til);
        mEdt_ip.setText(SPUtils.getIp());
        mEdt_port.setText(String.valueOf(SPUtils.getPort()));
        mEdt_unit.setText(String.valueOf(SPUtils.getUnit()));
        mEdt_usbtty.setText(SPUtils.getUsbtty());
        mEdt_rang.setText(String.valueOf(SPUtils.getRang()));

        this.findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SPUtils.saveIp(getIp());
                SPUtils.savePort(getPort());
                SPUtils.saveUnit(getUnit());
                SPUtils.saveUsbtty(getUsbtty());
                SPUtils.saveRang(getRang());
                if (m_ipTil.isErrorEnabled() || m_portTil.isErrorEnabled()) {
                    Toast.makeText(v.getContext(), "错误！", Toast.LENGTH_SHORT).show();
                    return;
                }
                mService.reboot();
                mDrawerLayout.closeDrawers();
            }
        });
        //设置探测到的串口地址列表
        m_ttyList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, m_ttyDevices));
        m_ttyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mEdt_usbtty.setText(m_ttyDevices[position]);
            }
        });
        //正则校验
        mEdt_ip.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!m_ipPattern.matcher(getIp()).matches()) {
                    m_ipTil.setErrorEnabled(true);
                    m_ipTil.setError("请正确输入");
                } else {
                    m_ipTil.setErrorEnabled(false);
                }
            }
        });
        mEdt_port.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    if (Integer.parseInt(s.toString()) >= 65535) {
                        m_ipTil.setErrorEnabled(true);
                        m_ipTil.setError("端口超过最大值65535");
                    } else {
                        m_ipTil.setErrorEnabled(false);
                    }
                } catch (NumberFormatException e) {
                    String defaultPort = String.valueOf(SPUtils.getPort());
                    mEdt_port.setText(defaultPort);
                    mEdt_port.setSelection(0, defaultPort.length());
                }
            }
        });

        mFabutton.setImageResource(R.mipmap.ic_launcher);
        mFabutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.openDrawer(Gravity.LEFT);
            }
        });
        mFabutton.setBackgroundResource(R.mipmap.ic_setting);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
            mDrawerLayout.closeDrawers();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent wifiServiceIntent = new Intent(this, WifiService.class);
        startService(wifiServiceIntent);
        try {
            if (mHandler != null) {
                mHandler.removeCallbacksAndMessages(null);
                mHandler = null;
            }
            if (mConn != null) {
                unbindService(mConn);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getIp() {
        return mEdt_ip.getText().toString().trim();
    }


    private String getPort() {
        return mEdt_port.getText().toString().trim();
    }


    private String getUnit() {
        return mEdt_unit.getText().toString().trim();
    }


    private String getRang() {
        return mEdt_rang.getText().toString().trim();
    }

    private String getUsbtty() {
        return mEdt_usbtty.getText().toString().trim();
    }
}
